import React, { useEffect, useRef, useState } from 'react'
import { Table, Button, Modal, Tree } from 'antd';
import { UnorderedListOutlined, DeleteOutlined } from '@ant-design/icons'
import { connect } from 'umi'
import _ from 'lodash'
import type { TreeProps } from 'antd/es/tree';

function RoleList(props: any) {
    const { dispatch, roleList, routeList } = props;
    // 保存选中的item数据
    const [currentItem,setCurrentItem]=useState(null);
    // 路由配置信息
    const [routes,setRoutes]=useState(routeList);
    // 角色信息状态
    const [roles, setRoles] = useState(roleList);
    // 删除按钮对话框是否显示，初始为false，不显示
    const [deleteOpen, setDeleteOpen] = useState(false);
    // 修改角色权限按钮对话框是否显示，初始为false，不显示
    const [modifyRoleOpen, setModifyRoleOpen] = useState(false);
    // 表格的loading
    const [loading, setLoading] = useState(false);
    //删除对话框的异步操作等待的loading
    const [DelConfirmLoading, setDelConfirmLoading] = useState(false);
    //修改角色权限对话框的异步操作等待的loading
    const [modifyConfirmLoading, setModifyConfirmLoading] = useState(false);
    const currentUserData:Array<any>=JSON.parse(localStorage.getItem('token') as string) 
    // 获取角色信息
    useEffect(() => {
        if (roleList?.length === 0) {
            setLoading(true);
            dispatch({
                type: 'StandBox/getRoleList',
                payload: {
                    setLoading
                }
            })
        }
        else {
            console.log('读缓存信息,roleList:', roleList);
            setRoles(roleList);
        }
    }, [roleList])
    //获取路由配置信息
    useEffect(() => {
        if (routeList?.length === 0) {
            setLoading(true);
            dispatch({
                type: 'StandBox/getRouteList',
                payload: {
                    setLoading
                }
            })
        }
        else {
            console.log('读缓存信息,routeList:', routeList);
            setRoutes(routeList);
        }
    }, [routeList])
    // 删除按钮点击回调事件
    const handelDeleteLimit = (item: any) => {
        setDelConfirmLoading(true);
        setLoading(true);
        dispatch({
            type: 'StandBox/deleteRoleList',
            payload: {
                roleItem: item,
                setLoading,
                setDelConfirmLoading,
                setDeleteOpen,
                roles: roleList
            }
        })
    }
    const handleDeleteCancel = () => {
        // 取消操作，关闭删除对话框
        setDeleteOpen(false)
    }
    // 修改权限树形控件选中触发的事件
    const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
        let newItem=_.cloneDeep(currentItem);
        (newItem as any).rights=checkedKeys
        setCurrentItem(newItem)
    };
    // 点击修改权限对话框取消按钮，是对话框消失
    const handleModifyCancel=()=>{
        setModifyRoleOpen(false)
    };
    // 修改角色权限对话框的确认按钮，执行的点击事件
    const handelModifyRole=async (item:any)=>{
        setLoading(true);
        setModifyConfirmLoading(true);
        await dispatch({
            type:'StandBox/modifyRoleList',
            payload:{
                roleItem:item,
                roles,
                setLoading,
                setModifyConfirmLoading,
                setModifyRoleOpen
            }
        })
        if(currentUserData.length>0){
            // 获取最新的用户信息数据
            await dispatch({
                type: 'StandBox/getCurrentUserData',
                payload: {
                    currentItem:currentUserData[0],
                }
            })
        }
        
    }
    const columns = [
        {
            title: 'ID',    //标题
            dataIndex: 'id',     //匹配的字段名 
            key: 'id',
            render: (id: string) => {
                return <b>{id}</b>
            }
        },
        {
            title: '角色名称',    //标题
            dataIndex: 'roleName',     //匹配的字段名 
            key: 'roleName',
            render: (roleName: string) => {
                return <span>{roleName}</span>
            }
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <>
                        <Button danger shape="circle" style={{ 'marginRight': '10px' }} icon={<DeleteOutlined />} onClick={() => {
                            setCurrentItem(item);
                            setDeleteOpen(true)
                        }}>
                        </Button>
                    </>
                    <Button type="primary" shape="circle" icon={<UnorderedListOutlined />} onClick={()=>{
                        setCurrentItem(item);
                        setModifyRoleOpen(true);
                    }}></Button>
                </div>)
            }
        }
    ];
    return (
        <div>
            <Table dataSource={roles} columns={columns} loading={loading} rowKey={(item) => item.id} sticky />
            {/* 删除的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.roleName}】删除`}
                open={deleteOpen}
                onOk={() => { handelDeleteLimit(currentItem) }}
                confirmLoading={DelConfirmLoading}
                onCancel={handleDeleteCancel}
                okText='确定'
                cancelText='取消'
            >
                <p>是否要删除该角色权限信息？</p>
            </Modal>

            {/* 修改角色路由权限的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.roleName}】修改角色权限`}
                open={modifyRoleOpen}
                onOk={() => { handelModifyRole(currentItem) }}
                confirmLoading={modifyConfirmLoading}
                onCancel={handleModifyCancel}
                okText='确定'
                cancelText='取消'
            >
                <Tree
                    checkable
                    checkedKeys={(currentItem as any)?.rights}
                    onCheck={onCheck}
                    treeData={routes}
                    checkStrictly={true}
                />
            </Modal>
        </div>
    )
}

const mapStateToProps = (state: any) => {
    return {
        roleList: state.StandBox.roleList,
        routeList: state.StandBox.routeList
    }
}

export default connect(mapStateToProps)(RoleList)